package role

import (
	"context"
	"fast-boot/app/api/admin/internal/svc"
	"fast-boot/app/api/admin/internal/types"
	"fast-boot/app/model"
	"fast-boot/common/xerr"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 修改角色
func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateLogic) Update(in *types.SysRoleFormReq) (resp *types.SysRoleFormResp, err error) {

	info := model.SysRoleModel{}
	l.svcCtx.GormClient.GormDb.First(&info, in.Id)

	if info.Id == 0 {
		logx.WithContext(l.ctx).Errorf("role不存在: %s", in.Id)
		return nil, xerr.NewErrMsg("role不存在")
	}
	if info.Name != in.Name {
		info.Name = in.Name
	}
	if info.Code != in.Code {
		info.Code = in.Code
	}
	if info.Sort != in.Sort {
		info.Sort = in.Sort
	}
	if info.Status != int8(in.Status) {
		info.Status = int8(in.Status)
	}
	if info.DataScope != int8(in.DataScope) {
		info.DataScope = int8(in.DataScope)
	}

	if err := l.svcCtx.GormClient.GormDb.Save(&info).Error; err != nil {
		return resp, err
	}

	return resp, nil
}
